import React, {useEffect, useMemo, useState} from 'react';
import {connect, Dispatch} from 'umi';
import {ConnectState, IResponse} from '@/models/connect';
import {Card, Dropdown, Menu, message, Select, Tag} from 'antd'
import {ArrowRightOutlined, CloseOutlined, DownOutlined} from '@ant-design/icons'
import FieldConfig from "@/pages/Analysis/components/GrobalFilter/FieldConfig";
import {IGrobalFilter, ITableGrobalFilter} from "@/pages/Analysis/components/GrobalFilter/type";
import FilterRelationship from "@/pages/Analysis/components/GrobalFilter/FilterRelationship";
import {PanelsParentItem} from "@/pages/SelfQuery/type";
import {queryGrobalFilterByUrl} from "@/services/analysis";
import ModalBox from "@/components/ModalBox";

const {Option} = Select;
require("./index.less")

interface IProps {
  dispatch: Dispatch;
  project: PanelsParentItem
  onCanel: () => void
  sheetList: any[]
  visible: boolean

}

const clientWidth = document.body.clientWidth
let filterRelationship: {} | null | undefined = null
const GrobalFilter: React.FC<IProps> = (props) => {
  const {
    dispatch, sheetList, project, visible, onCanel
  }
    = props
  const {projectId, projectName} = project
  const modalWidth = clientWidth
  const [viewKey, setViewKey] = useState<string>("0");
  const [fieldConfigVisible, setFieldConfigVisible] = useState<boolean>(false);
  const [currentEditingItem, setCurrentEditingItem] = useState<IGrobalFilter | null>(null);
  const [selectTags, setSelectTags] = useState<IGrobalFilter[]>([]); // 展开指定的树节点
  const [dragBgColor, setDragBgColor] = useState<{}>({}); // 拖动背景色

  const projectSheetList = sheetList ? sheetList.filter(v => v.projectId === projectId) : []
  useEffect(() => {
    queryGrobalFilterByUrl({projectId}).then((res: IResponse) => {
      const {payload}= res
      const datas = payload.map((value:ITableGrobalFilter) => {
        const {name, viewId, config} = value
        const view = projectSheetList.find(v => v.id === viewId)
        const data = {
          column: name,
          alias: JSON.parse(config).alias,
          viewId,
          viewName: view.name,
          config: JSON.parse(view.model)[name],
        }
        return data;
      })
      setSelectTags(datas)
    })
  }, [projectId]);
  useMemo(() => {
    const datas: any[] = []
    selectTags.forEach(value => {
      const {column, alias, viewId, viewName} = value
      let children: any[] = []
      projectSheetList.filter(p => p.id != viewId).forEach((v: any, i: number) => {
          const model = JSON.parse(v.model)
          const {name, id} = v
          let keys = Object.keys(model)
          keys.forEach(key => {
            if (key == column) {
              children.push({id: `${key}${id}`, name: key, viewName: name})
            }
          })

        }
      )
      const data = {
        id: `${column}${viewId}`,
        name: alias && alias != '' ? alias : column,
        viewName: viewName,
        children: children,
      }
      datas.push(data)
    })
    const datasource = {id: "0", name: '根节点', viewName: '', children: datas}
    filterRelationship = <FilterRelationship width={modalWidth * 0.60 - 24}
                                             data={datasource}/>
  }, [selectTags])
  const tabList = projectSheetList.map((v: any, i: number) => {
    return {key: i.toString(), tab: v.name}
  })
  const contentList = projectSheetList.map((v: any, i: number) => {
      const {model} = v
      let keys = Object.keys(JSON.parse(model))
      keys = keys.filter(i => {
        return selectTags.filter(j => j.column == i).length == 0
      })
      const content = (
        <div style={{ overflowY: 'auto'}}>
          {keys.map((key: string) => {
            return <Tag key={key} color="default" draggable={true}
                        onDragStart={(e) => dragStart(e, v, key)}
                        onDragEnd={() => {
                          setDragBgColor({})
                        }}
            >{key}</Tag>
          })}
        </div>
      )
      return content
    }
  )

// 拖拽开始
  const dragStart = (e: any, item: any, key: any) => {
    e.dataTransfer.setData('item', JSON.stringify(item));// 拖拽元素携带的数据
    e.dataTransfer.setData('key', key);// 拖拽元素携带的数据
    setDragBgColor({background: 'rgba(27,157,224,0.2)'})
  }

// 拖拽元素经过放置元素时
  const dragOver = (e: any) => {
    e.preventDefault();// 此处的代码是必须的  不然无法拖拽
  }

// 拖拽元素放到放置元素时
  const drop = (e: any) => {
    e.preventDefault();
    // 放置之后的后续操作
    const item = JSON.parse(e.dataTransfer.getData("item"))
    const model = JSON.parse(item.model)
    const key = e.dataTransfer.getData("key")
    if (selectTags.length == 0 || selectTags.filter((v) => v.column == key).length == 0) {
      setSelectTags([...selectTags,
        {column: key, config: model[key], viewId: item.id, viewName: item.name}])
    }
    setDragBgColor({})
  }
  const onTagClose = (key: any) => {
    const list = selectTags.filter(v => v.column != key)
    setSelectTags(list)
  }

  const fieldConfigShow = (item: IGrobalFilter) => {
    setCurrentEditingItem(item)
    setFieldConfigVisible(true)
  }
  const closeFieldConfig = () => {
    setCurrentEditingItem(null)
    setFieldConfigVisible(false)
  }
  const onSaveFieldConfig = ({column, alias}: any) => {

    const selectTagList = [...selectTags].map(v => {
      if (v.column == column) {
        v.alias = alias
      }
      return v
    })
    setSelectTags(selectTagList)
    closeFieldConfig()
  }

  const filterWithDropdownList = () => {
    const menuClicks = [{key: 1, name: '字段设置', func: fieldConfigShow}]
    const onClick = (key: any, item: IGrobalFilter) => {
      menuClicks.filter(value => value.key == key)[0].func(item)
    };
    const menu = (item: IGrobalFilter) => (
      <Menu onClick={({key}) => onClick(key, item)}>
        {menuClicks.map((v: any) => {
          return (
            <Menu.Item key={v.key}>
              {v.name}
            </Menu.Item>
          )
        })}

      </Menu>
    );
    const content = selectTags && selectTags.length > 0 ?
      selectTags.map((v) => {
        const {column, alias} = v
        const name = `${column}${alias && alias != '' ? `[${alias}]` : ''}`
        return (
          <Dropdown
            key={column}
            overlay={menu(v)}
            trigger={['click']}
          >
            <div className='dragTag'>
              <DownOutlined/>
              {name}
              <CloseOutlined onClick={() => onTagClose(column)}/>
            </div>
          </Dropdown>
        )
      })
      : <p>
        <ArrowRightOutlined/>
        <span>请拖拽到这里</span>
      </p>
    return content
  }

  const dropBoxContents = () => {
    const contents = [
      // {id: 1, label: '维度切换', content: filterWithDropdownList()},
      {id: 2, label: '全局筛选', content: filterWithDropdownList()},
    ]
    return (
      <div>
        {contents.map((content) => {
          return (
            <div key={content.id}>
              <div>
                {content.label}
              </div>
              <div className='dropBox' style={{...dragBgColor}}>
                {content.content}
              </div>
            </div>
          )
        })}
      </div>
    )
  }

  const viewSelect = <Select defaultValue="0" onChange={key => {
    setViewKey(key)
  }}>
    {
      tabList.map(value => {
        return <Option value={value.key}>{value.tab}</Option>

      })
    }
  </Select>
  const onSave = () => {
    dispatch({
      type: 'board/setGrobalFilter',
      payload: {
        projectId: projectId, columns: selectTags.map(v => {
          return {viewId: v.viewId, name: v.column, config: JSON.stringify({alias: v.alias})}
        })
      },
      callback: (res: IResponse) => {
        const {header} = res;
        if (header.code === 200) {
          message.success('修改成功');
        } else {
          message.warning('修改失败');
        }
      },
    })
  }
  return (
    <ModalBox
      title={`全局控制器(${projectName})`}
      visible={visible}
      onCancel={onCanel}
      onOk={onSave}
    >
      {currentEditingItem ?
        [<FieldConfig
          key={currentEditingItem.column}
          currentEditingItem={currentEditingItem}
          visible={fieldConfigVisible}
          onSave={onSaveFieldConfig}
          onCancel={closeFieldConfig}
        />]
        : null}
      <div style={{display: 'flex',height:"100%"}}>
        <div style={{display: 'flex'}}>
          <Card
            style={{width: modalWidth * 0.20}}
            title={viewSelect}
          >
            {contentList[viewKey]}
          </Card>
          <Card
            style={{width: modalWidth * 0.20}}
            onDrop={(e: any) => drop(e)}
            onDragOver={(e: any) => dragOver(e)}>
            {dropBoxContents()}
          </Card>
        </div>
        <Card>
          <div>
            {filterRelationship}
          </div>
        </Card>
      </div>
    </ModalBox>
  );
};
export default connect(({sheet, dataRole}: ConnectState) => ({
  sheetList: sheet.sheetList
}))(GrobalFilter);
